﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AuthApi.Contracts;
using Web.Framework;
using WebAppAuthAdmin.Code;
using WebAppAuthAdmin.Code.Security;

namespace WebAppAuthAdmin.App
{
    public partial class UserCreate : BasePage
    {
        private int? ApplicationId
        {
            get
            {
                return (int?)ViewState["ApplicationId"];
            }
            set
            {
                ViewState["ApplicationId"] = value;
            }
        }

        private List<WebApplicationInfo> applicationList
        {
            get
            {
                return (List<WebApplicationInfo>)ViewState["applicationList"];
            }
            set
            {
                ViewState["applicationList"] = value;
            }
        }

        private List<LinkButton> actionButtons = new List<LinkButton>();
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            LinkButton crearContactoButton = new LinkButton();
            crearContactoButton.ID = "guardar";
            crearContactoButton.Text = "Guardar";
            crearContactoButton.Click += new EventHandler(lnkGuardar_Click);
            actionButtons.Add(crearContactoButton);

            base.LoadContextActions(actionButtons);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                if (!this.IsPostBack)
                {
                    string paramApplicationId = this.Request.QueryString["applicationId"];
                    if (!String.IsNullOrEmpty(paramApplicationId))
                    {
                        ApplicationId = Convert.ToInt32(paramApplicationId);

                    }

                    Bind();
                }

                HasPermissionToSeeMe(AppSecurity.APP_USER_CREATE + ApplicationId.ToString());
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        private void Bind()
        {
            applicationList = WebServiceHelper.GetApplicationList(string.Empty);
            this.GridApplication.DataSource = applicationList;
            this.GridApplication.DataBind();
        }

        protected override void ApplySecurity()
        {
            bool userCreate = HasPermissionFor(AppSecurity.APP_USER_CREATE);
            actionButtons.Where(a => a.ID == "guardar").Single().Visible = userCreate;
            this.lnkGuardar.Visible = userCreate;
        }

        protected void GridCustomer_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            try
            {
                if (e.Row.RowType == DataControlRowType.DataRow)
                {
                    WebApplicationInfo application = (WebApplicationInfo)e.Row.DataItem;

                    if (ApplicationId.HasValue)
                    {
                        if (ApplicationId == application.Id)
                        {
                            CheckBox chkSelect = (CheckBox)e.Row.Cells[0].FindControl("chkSelectRow");
                            chkSelect.Checked = true;
                            this.hidCheckedRows.Value = string.Format("#{0}#", application.Id);
                        }
                    }

                    if (!HasPermissionFor(AppSecurity.APP_USER_CREATE + application.Id.ToString()))
                    {
                        e.Row.Visible = false;
                    }
                }
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }

        protected void GridApplication_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            try
            {
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }       

        protected void lnkGuardar_Click(object sender, EventArgs e)
        {
            try
            {
                UserWithApplication user = new UserWithApplication();
                user.GivenName = this.txtNombreUsuario.Text;
                user.Password = this.txtPassword.Text;
                user.UserName = this.txtUserName.Text.ToLower();

                List<int> selectedRowsIds = UIHelper.GetSelectedRowIds(this.hidCheckedRows.Value);

                foreach (int i in selectedRowsIds)
                {
                    user.WebApplicationList.Add(new WebApplicationInfoIncluded()
                    { IsIncluded = true, 
                      Id = i,
                      CompanyId = this.GetSingleContextCompany().Id });
                }

                user = WebServiceHelper.CreateUser(user);

                string redirect = string.Format("/App/UserViewApplications.aspx?userName={0}", Server.UrlEncode(user.UserName));
                if (user.UsuarioExistente)
                {
                    redirect += "&existente=1";
                    if (ApplicationId.HasValue)
                    {
                        redirect += string.Format("&applicationId={0}", ApplicationId.Value);
                    }
                }

                // Si está todo bien, redirigo a la edicion por aplicación
                this.Response.Redirect(redirect, true);
            }
            catch (Exception ex)
            {
                ExceptionManager.Instance.HandleException(ex);
            }
        }
    }
}